package com.moyu.crowdsource.security.login;

import com.moyu.crowdsource.entity.AccountUser;
import com.moyu.crowdsource.service.AccountUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.social.security.SocialUserDetails;
import org.springframework.social.security.SocialUserDetailsService;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class MyUserDetails implements UserDetailsService,SocialUserDetailsService {

  @Autowired(required = true)
  AccountUserService accountUserService;

  private Logger logger = LoggerFactory.getLogger(getClass());

  @Override
  public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
    // Student student =studentMapper.selectByPrimaryKey(s);
    logger.info("登录名:" + username);
    return buildUser(username);
  }

  @Override
  public SocialUserDetails loadUserByUserId(String userId) throws UsernameNotFoundException {
    logger.info("登录名:" + userId);
    return buildUser(userId);
  }

  private SocialUserDetails buildUser(String userId) {
   AccountUser user = null;
    List<AccountUser> list = accountUserService.getAccountByAccountUsername(userId);
    if (list != null && list.size() > 0) {
      user = list.get(0);
    }
    if (user == null) {
      throw new UsernameNotFoundException("用户名不存在");
    }
    return user;

  }
}
